package cn.fl.car300.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.car300.condition.InfCar300RecQueryCondition;
import cn.fl.car300.constant.InfCar300RecConstant;
import cn.fl.car300.service.IInfCar300RecService;
import cn.fl.car300.vo.InfCar300RecVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.transform.PrjPrdDtlVOTransform;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;

/**
 * @Description: 二手车评估表 控制层
 */
@Controller
@RequestMapping("/car300/infCar300Rec")
public class InfCar300RecController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InfCar300RecController.class);

	/**
	 * InfCar300Rec 服务层BEAN
	 */
	@Autowired
	private IInfCar300RecService infCar300RecService;
	
	/**
	 * PrjPrdDtl 服务层BEAN
	 */
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;
	
	/**
	 * SysUlFilesRec 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("car300/infCar300Rec/oldReportListPage");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("car300/infCar300Rec/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String vin = request.getParameter("vin");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		InfCar300RecQueryCondition qc = new InfCar300RecQueryCondition();
		if (StringUtils.isNotEmpty(vin)) {
			qc.setVin(vin);
		}
		page.setCondition(qc);
		
		Pager pager = this.infCar300RecService.searchListPage(page);
		List<InfCar300RecVO> list = (List<InfCar300RecVO>) pager.getResultList();
		ListPageVO<InfCar300RecVO> listPage = new ListPageVO<InfCar300RecVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.infCar300RecService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			InfCar300RecVO vo = this.infCar300RecService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		InfCar300RecVO entity = null;
		try {
			entity = new InfCar300RecVO();
			//TODO ADD PARAM
			Long id = this.infCar300RecService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		//String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		InfCar300RecVO entity = null;
		try {
			entity = new InfCar300RecVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.infCar300RecService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	
	/**
	 * 到二手车报告列表页面
	 */
	@RequestMapping(value = "/toReportListPage.do", method = { RequestMethod.GET})
	public ModelAndView toReportListPage(HttpServletRequest request, HttpServletResponse response) {
		String prjId = request.getParameter("prjId");
		String isGetReport = request.getParameter("isGetReport");//是否能获取报告
		InfCar300RecQueryCondition qc = new InfCar300RecQueryCondition();
		ModelAndView view = new ModelAndView("car300/infCar300Rec/oldReportList");
		if(StringUtils.isEmpty(prjId)){
			BaseLogUtils.info(logger, "toReportListPage", "获取报告,项目ID不存在.[prjId="+prjId+"]", CurrentThreadContext.getCurrentUserName());
			view.addObject("flag", "no");
			view.addObject("info", "项目ID不存在！");
		}else{
			view.addObject("flag", "yes");
			qc.setPrjId(Long.parseLong(prjId));//项目ID
			//根据项目ID查询产品明细列表信息
        	PrjPrdDtlQueryCondition condition = new PrjPrdDtlQueryCondition();
        	condition.setPrjId(Long.parseLong(prjId));
        	List<PrjPrdDtlVO> plist = this.prjPrdDtlService.selectList(condition);
        	qc.setPrjPrdDtlList(PrjPrdDtlVOTransform.toDTOList(plist));

			//信审员审批节点可获取二手车评估报告
			if(StringUtils.isNotEmpty(isGetReport) && "true".equals(isGetReport)){
				qc.setCurrentUserName(CurrentThreadContext.getCurrentUserName());
				qc.setCurrentUserId(CurrentThreadContext.getCurrentUserId());
				this.infCar300RecService.makeOldCarReport(qc);
				BaseLogUtils.info(logger, "toReportListPage", "获取二手车报告中.....[prjId="+prjId+"]", CurrentThreadContext.getCurrentUserName());
			}
			
			//循环生成，按项目查询设备
			List<InfCar300RecVO> reList = new ArrayList<InfCar300RecVO>();
			if(CollectionUtils.isNotEmpty(plist) && plist.size()>0){
        		for(PrjPrdDtlVO vo : plist){
        			//VIN作为唯一值如果空-则跳过
        			if (StringUtils.isEmpty(vo.getVin())) {
        				continue;
        			}
        			//查询数据库，如果存在日期相同的评估报告，则不保存，直接跳过
        			qc.setVin(vo.getVin());
        			List<InfCar300RecVO> vinList = this.infCar300RecService.searchList(qc);
        			if(CollectionUtils.isNotEmpty(vinList) && vinList.size()>0){
        				reList.add(vinList.get(0));
        			}
        		}
			}
			if(reList.size()<1){
				view.addObject("flag", "no");
				view.addObject("info","没有报告！");
			}
			view.addObject("reList", reList);
		}
		BaseLogUtils.info(logger, "toReportListPage", "跳转到二手车报告列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到二手车报告详情页面
	 */
	@RequestMapping(value = "/toReportViewPage.do", method = { RequestMethod.GET})
	public ModelAndView toReportViewPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String vin = request.getParameter("vin");
		InfCar300RecQueryCondition qc = new InfCar300RecQueryCondition();//报告
		SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();//文件
		ModelAndView view = new ModelAndView("car300/infCar300Rec/oldReportView");
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "toReportViewPage", "获取报告,主键ID不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			view.addObject("flag", "no");
			view.addObject("info", "报告主键ID不存在！");
		}else{
			view.addObject("flag", "yes");
			qc.setId(Long.parseLong(id));//主键ID
			qc.setVin(vin);//车架号
			//查询二手车报告
			List<InfCar300RecVO> vinList = this.infCar300RecService.searchList(qc);
			InfCar300RecVO reMap = new InfCar300RecVO();
			if(CollectionUtils.isNotEmpty(vinList) && vinList.size()>0){
				reMap = vinList.get(0);
				//设置车辆照片公用属性-作为查询条件
				condition.setSysCd(InfCar300RecConstant.INF_CAR300_SYSCD);
				condition.setOrgCd(InfCar300RecConstant.INF_CAR300_ORGCD);
				condition.setCfgCd(InfCar300RecConstant.INF_CAR300_CFGCD);
				condition.setTabNm(InfCar300RecConstant.INF_CAR300_TABNM);
    			//查询车辆照片和报告PDF附件列表
    			condition.setPkId(reMap.getId().toString());
				condition.setCfgDtlCd(InfCar300RecConstant.INF_CAR300_CFGDTLCD_10);
    			List<SysUlFilesRecVO> photoList = this.sysUlFilesRecService.searchList(condition);
    			reMap.setPhotoList(photoList);//车辆照片列表
				condition.setCfgDtlCd(InfCar300RecConstant.INF_CAR300_CFGDTLCD_20);
				List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);
				if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
					String pdfUrlBen = filesList.get(0).getFilePath();
					reMap.setPdfUrlBen(pdfUrlBen);//本地PDF下载路径
				}
    			reMap.setFilesList(filesList);//报告PDF列表
    			view.addObject("reMap", reMap);//返回第一条数据
			}else{
				view.addObject("flag", "no");
				view.addObject("info","没有报告！");
			}
		}
		BaseLogUtils.info(logger, "toReportViewPage", "跳转到二手车报告详情页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
}

